<template>
	<view class="container">
		<view class="detail-content" v-if="youhuiList">
			<!-- 标题和发布者信息 -->
			<view class="header-info">
				<view class="title">
					<span>{{ youhuiList.title }}</span>
				</view>
				<view class="publisher-info">
					<text class="publisher">发布者：{{ youhuiList.publisher || youhuiList.merchant }}</text>
					<text class="publish-time">{{ formatDateTime(youhuiList.time || youhuiList.issusTime) }}</text>
				</view>
			</view>
			
			<!-- 预览图 -->
			<view class="preview-image">
				<image :src="youhuiList.img || youhuiList.url || '/static/tuangou-youhui/优惠卷.png'" mode="aspectFill"></image>
			</view>
			
			<!-- 内容介绍 -->
			<view class="content-section">
				<view class="section-title">活动介绍</view>
				<view class="content-text">{{ stripHtmlTags(youhuiList.content) }}</view>
			</view>
			
			<!-- 价格信息 -->
			<view class="price-section">
				<view class="section-title">价格信息</view>
				<view class="price-info">
					<view class="price-item">
						<text class="price-label">优惠价：</text>
						<text class="present-price">￥{{ youhuiList.presentPrice || youhuiList.price }}</text>
					</view>
					<view class="price-item" v-if="youhuiList.originalPrice || youhuiList.Oprice">
						<text class="price-label">原价：</text>
						<text class="original-price">￥{{ youhuiList.originalPrice || youhuiList.Oprice }}</text>
					</view>
					<view class="price-item" v-if="(youhuiList.originalPrice || youhuiList.Oprice) && (youhuiList.presentPrice || youhuiList.price)">
						<text class="price-label">优惠：</text>
						<text class="discount-amount">省￥{{ ((youhuiList.originalPrice || youhuiList.Oprice) - (youhuiList.presentPrice || youhuiList.price)).toFixed(2) }}</text>
					</view>
				</view>
			</view>
			
			<!-- 时间信息 -->
			<view class="time-section">
				<view class="section-title">活动时间</view>
				<view class="time-info">
					<view class="time-item">
						<text class="time-label">截止时间：</text>
						<text class="time-value">{{ formatDate(youhuiList.endTime || youhuiList.end) }}</text>
					</view>
					<view class="time-item">
						<text class="time-label">发布时间：</text>
						<text class="time-value">{{ formatDate(youhuiList.time || youhuiList.issusTime) }}</text>
					</view>
				</view>
			</view>
			
			<!-- 联系方式 -->
			<view class="contact-section" v-if="youhuiList.telephone || youhuiList.tel">
				<view class="section-title">联系方式</view>
				<view class="contact-info">
					<view class="contact-item" @click="makePhoneCall">
						<text class="contact-label">咨询电话：</text>
						<text class="contact-value phone">{{ youhuiList.telephone || youhuiList.tel }}</text>
						<text class="call-btn">拨打</text>
					</view>
				</view>
			</view>
			
			<!-- 注意事项 -->
			<view class="note-section" v-if="youhuiList.note || youhuiList.attention">
				<view class="section-title">注意事项</view>
				<view class="note-content">{{ stripHtmlTags(youhuiList.note || youhuiList.attention) }}</view>
			</view>
			
			<!-- 统计信息 -->
			<view class="stats-section">
				<view class="stats-item">
					<text class="stats-label">阅读量：</text>
					<text class="stats-value read-count">{{ youhuiList.num || 0 }}</text>
				</view>
				<view class="stats-item">
					<text class="stats-label">参与人数：</text>
					<text class="stats-value participants">{{ youhuiList.participants || 0 }}</text>
				</view>
			</view>
			
			<!-- 参与按钮 -->
			<view class="participate-section" v-if="!isExpired">
				<button class="participate-btn" @click="handleParticipate" :disabled="participating">
					{{ participating ? '参与中...' : '立即参与' }}
				</button>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-state" v-else-if="loading">
			<uni-load-more status="loading"></uni-load-more>
		</view>
		
		<!-- 错误状态 -->
		<view class="error-state" v-else>
			<image src="/static/tuangou-youhui/优惠卷.png" mode="aspectFit"></image>
			<text>加载失败，请重试</text>
			<button class="retry-btn" @click="loadDetail">重试</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				youhuiList: null,
				loading: false,
				groupId: null,
				participating: false,
				// API基础地址 - 直接访问后端服务
				baseUrl: 'http://localhost:9201',
				// 是否启用真实API（设为false时直接使用模拟数据）
				// 要启用真实API，需要：
				// 1. 确保后端服务正在运行
				// 2. 配置正确的baseUrl
				// 3. 确保接口不需要权限或已配置白名单
				// 4. 将此值设为true
				useRealApi: true
			}
		},
		computed: {
			// 检查是否已过期
			isExpired() {
				if (!this.youhuiList || !this.youhuiList.endTime) {
					return false;
				}
				const endTime = new Date(this.youhuiList.endTime);
				const now = new Date();
				return endTime < now;
			}
		},
		onLoad(options) {
			if (options.id) {
				this.groupId = options.id;
				this.loadDetail();
			} else {
				// 如果没有ID参数，使用模拟数据
				this.youhuiList = this.getMockDetail();
			}
		},
		methods: {
			// 加载详情
			async loadDetail() {
				this.loading = true;
				try {
					// 如果禁用真实API，直接使用模拟数据
					if (!this.useRealApi) {
						console.log('使用模拟数据模式');
						this.youhuiList = this.getMockDetail();
						return;
					}
					
					// 调用API接口
					const response = await this.getGroupBuyingDetailApi(this.groupId);
					
					// 处理API返回的数据结构
					// 检查是否有错误码
					if (response && response.code && response.code !== 200) {
						console.log('API返回错误:', response.msg);
						throw new Error(response.msg || 'API调用失败');
					}
					
					if (response && response.data) {
						this.youhuiList = response.data;
					} else if (response) {
						this.youhuiList = response;
					} else {
						throw new Error('API返回数据格式错误');
					}
					
					// 阅读量已在获取详情时自动增加，无需单独调用
				} catch (error) {
					// 如果API调用失败，使用模拟数据
					this.youhuiList = this.getMockDetail();
					
					let errorMsg = '网络异常，显示模拟数据';
					if (error.message.includes('未授权')) {
						errorMsg = '需要登录才能查看团购详情，显示模拟数据';
					} else if (error.message.includes('权限不足')) {
						errorMsg = '权限不足，显示模拟数据';
					} else if (error.message.includes('接口不存在')) {
						errorMsg = '接口暂未开放，显示模拟数据';
					}
					
					uni.showToast({
						title: errorMsg,
						icon: 'none',
						duration: 3000
					});
				} finally {
					this.loading = false;
				}
			},
			
			// API调用方法
			getGroupBuyingDetailApi(id) {
				return new Promise((resolve, reject) => {
					// 获取token
					const token = uni.getStorageSync('token') || uni.getStorageSync('access_token');
					
					uni.request({
						url: `${this.baseUrl}/system/buying/public/${id}`,
						method: 'GET',
						header: {
							'Content-Type': 'application/json',
							'Authorization': token ? `Bearer ${token}` : ''
						},
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res.data);
							} else if (res.statusCode === 401) {
								reject(new Error('未授权，请先登录'));
							} else if (res.statusCode === 403) {
								reject(new Error('权限不足'));
							} else if (res.statusCode === 404) {
								reject(new Error('接口不存在'));
							} else {
								reject(new Error(`请求失败: ${res.statusCode} - ${res.data?.msg || '未知错误'}`));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			
			
			// 模拟详情数据
			getMockDetail() {
				return {
					id: parseInt(this.groupId) || 1,
					title: "汽车惠民活动走进群众生活",
					publisher: "济源某某汽车行业",
					merchant: "济源某某汽车行业",
					time: "2024-01-15 10:30:00",
					issusTime: "2024/1/15 10:30",
					img: "/static/tuangou-youhui/优惠卷.png",
					url: "/static/tuangou-youhui/优惠卷.png",
					content: "哇噻！羊毛的看过来！易车修汽车维修服务中心出优惠团购了！纯手工洗车只要25元一次，还增20元油券，够意思了吧！哇噻！婷羊毛的看过来！易车修汽车维修服务中心出优惠团购了！纯手工洗车只要25元一次，还增20元油劵，够意思了吧",
					originalPrice: 45.00,
					presentPrice: 25.00,
					price: "25.00",
					Oprice: "45.00",
					endTime: "2024-04-10 23:59:59",
					end: "2024/4/10",
					star: "2024/1/15",
					telephone: "0391-1234567",
					tel: "0391-1234567",
					note: "本活动仅限新用户，每人限购一次，活动期间有效",
					attention: "本活动仅限新用户，每人限购一次，活动期间有效",
					num: 1250,
					deleted: 0
				};
			},
			
			
			// 拨打电话
			makePhoneCall() {
				const phoneNumber = this.youhuiList.telephone || this.youhuiList.tel;
				if (phoneNumber) {
					uni.makePhoneCall({
						phoneNumber: phoneNumber,
						fail: (err) => {
							console.error('拨打电话失败:', err);
							uni.showToast({
								title: '拨打电话失败',
								icon: 'none'
							});
						}
					});
				}
			},
			
			// 格式化日期时间
			formatDateTime(dateStr) {
				if (!dateStr) return '';
				const date = new Date(dateStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				const date = new Date(dateStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			
			// 参与团购
			async handleParticipate() {
				if (this.participating) return;
				
				// 检查是否已过期
				if (this.isExpired) {
					uni.showToast({
						title: '团购已过期',
						icon: 'none'
					});
					return;
				}
				
				this.participating = true;
				
				try {
					// 调用参与API
					await this.participateGroupBuyingApi(this.groupId);
					
					// 本地更新参与人数
					if (this.youhuiList) {
						this.youhuiList.participants = (this.youhuiList.participants || 0) + 1;
					}
					
					// 设置全局标记，表示数据已更新
					const app = getApp();
					app.globalData.groupBuyDataUpdated = true;
					app.globalData.updatedGroupBuyId = this.groupId;
					app.globalData.updatedParticipants = this.youhuiList.participants;
					
					uni.showToast({
						title: '参与成功！',
						icon: 'success'
					});
				} catch (error) {
					uni.showToast({
						title: error.message || '参与失败，请重试',
						icon: 'none'
					});
				} finally {
					this.participating = false;
				}
			},
			
			// 参与团购API
			participateGroupBuyingApi(id) {
				return new Promise((resolve, reject) => {
					// 获取token
					const token = uni.getStorageSync('token') || uni.getStorageSync('access_token');
					
					uni.request({
						url: `${this.baseUrl}/system/buying/public/${id}/participate`,
						method: 'POST',
						header: {
							'Content-Type': 'application/json',
							'Authorization': token ? `Bearer ${token}` : ''
						},
						data: {
							userName: '用户', // 可以后续从用户信息获取
							phone: '', // 可以后续从用户信息获取
							remark: '通过小程序参与'
						},
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res.data);
							} else if (res.statusCode === 401) {
								reject(new Error('未授权，请先登录'));
							} else if (res.statusCode === 403) {
								reject(new Error('权限不足'));
							} else if (res.statusCode === 404) {
								reject(new Error('团购不存在'));
							} else {
								reject(new Error(`参与失败: ${res.statusCode} - ${res.data?.msg || '未知错误'}`));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},
			
			// 过滤HTML标签
			stripHtmlTags(html) {
				if (!html) return '';
				// 使用正则表达式移除HTML标签
				return html.replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#39;/g, "'");
			}
		}
	}
</script>

<style>
	.container {
		background: linear-gradient(to bottom, #3284fc 350rpx, transparent 350rpx);
		min-height: 100vh;
		padding: 10rpx 20rpx;
		box-sizing: border-box;
	}
	
	.detail-content {
		margin-top: 20rpx;
	}
	
	.header-info {
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	}
	
	.title {
		text-align: center;
		margin: 10rpx 0 20rpx 0;
	}
	
	.title span {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		line-height: 1.4;
	}
	
	.publisher-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.publisher {
		font-size: 24rpx;
		color: #666;
	}
	
	.publish-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.preview-image {
		background: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	}
	
	.preview-image image {
		width: 100%;
		height: 400rpx;
		border-radius: 10rpx;
	}
	
	.content-section,
	.price-section,
	.time-section,
	.contact-section,
	.note-section,
	.stats-section {
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 20rpx;
		border-left: 6rpx solid #3284fc;
		padding-left: 20rpx;
	}
	
	.content-text {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}
	
	.price-info {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}
	
	.price-item {
		display: flex;
		align-items: center;
	}
	
	.price-label {
		font-size: 28rpx;
		color: #666;
		margin-right: 20rpx;
		min-width: 120rpx;
	}
	
	.present-price {
		font-size: 36rpx;
		font-weight: 600;
		color: #ff4757;
	}
	
	.original-price {
		font-size: 28rpx;
		color: #999;
		text-decoration: line-through;
	}
	
	.discount-amount {
		font-size: 28rpx;
		color: #52c41a;
		font-weight: 600;
	}
	
	.time-info {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}
	
	.time-item {
		display: flex;
		align-items: center;
	}
	
	.time-label {
		font-size: 28rpx;
		color: #666;
		margin-right: 20rpx;
		min-width: 120rpx;
	}
	
	.time-value {
		font-size: 28rpx;
		color: #333;
	}
	
	.contact-info {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}
	
	.contact-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background: #f8f9fa;
		border-radius: 10rpx;
	}
	
	.contact-label {
		font-size: 28rpx;
		color: #666;
		margin-right: 20rpx;
		min-width: 120rpx;
	}
	
	.contact-value {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}
	
	.phone {
		color: #3284fc;
	}
	
	.call-btn {
		font-size: 24rpx;
		color: #3284fc;
		padding: 10rpx 20rpx;
		border: 1rpx solid #3284fc;
		border-radius: 20rpx;
	}
	
	.note-content {
		font-size: 26rpx;
		color: #666;
		line-height: 1.6;
		white-space: pre-line;
	}
	
	.stats-item {
		display: flex;
		align-items: center;
	}
	
	.stats-label {
		font-size: 28rpx;
		color: #666;
		margin-right: 20rpx;
	}
	
	.stats-value {
		font-size: 28rpx;
		color: #333;
		font-weight: 600;
	}
	
	.read-count {
		color: #3284fc;
	}
	
	.participants {
		color: #ff6b35;
	}
	
	.participate-section {
		margin-top: 30rpx;
		padding: 0 20rpx;
	}
	
	.participate-btn {
		width: 100%;
		height: 80rpx;
		background: linear-gradient(135deg, #3284fc, #1e88e5);
		color: #fff;
		border: none;
		border-radius: 40rpx;
		font-size: 32rpx;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 8rpx 20rpx rgba(50, 132, 252, 0.3);
		transition: all 0.3s ease;
	}
	
	.participate-btn:disabled {
		background: #ccc;
		box-shadow: none;
	}
	
	.participate-btn:active {
		transform: translateY(2rpx);
		box-shadow: 0 4rpx 10rpx rgba(50, 132, 252, 0.3);
	}
	
	.loading-state {
		display: flex;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.error-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.error-state image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
		opacity: 0.5;
	}
	
	.error-state text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 30rpx;
	}
	
	.retry-btn {
		background: #3284fc;
		color: #fff;
		border: none;
		border-radius: 20rpx;
		padding: 20rpx 40rpx;
		font-size: 28rpx;
	}
</style>